package com.hzlx.config;

import com.hzlx.dto.UserDto;
import com.hzlx.service.UserService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class LoginReactiveAuthenticationManager implements ReactiveAuthenticationManager {
    @Resource
    private final UserService userService;
    @Resource
    private final PasswordEncoder passwordEncoder;
    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
       String account = authentication.getName();
       String password = (String) authentication.getCredentials();
       UserDto userDto = userService.findByUserName(account);
       if (userDto != null && passwordEncoder.matches(password,userDto.getPassword())){
           List<GrantedAuthority> authorities = userDto.getAuthorities().stream()
                   .map(auth->new SimpleGrantedAuthority(auth))
                   .collect(Collectors.toList());
           UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(account,null,authorities);
           auth.setDetails(userDto);
           return Mono.just(auth);
       }else {
           return Mono.error(new BadCredentialsException("用户名或密码错误！"));
       }
    }
}
